import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
import { ChannelService } from './channel.service';
import { Channel } from './channel.entity';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { UseLog } from 'src/log/useLog.decorator';
import { In } from 'typeorm';
import { DeptService } from 'src/dept/dept.service';

@Controller('api/channel')
@ApiTags("渠道记录")
@UseGuards(AuthGuard("jwt"))
export class ChannelController {
    constructor(
        private readonly channelService: ChannelService,
        private readonly deptService: DeptService
    ) { }

    @Get(":name/get")
    @ApiOperation({ summary: "获取记录" })
    get(
        @CurrentUser() user: UserSys,
        @Param("name") name,
    ) {
        return this.channelService.channel.find({
            where: {
                system: {
                    id: user.system.id
                },
                dept: {
                    name
                }
            },
            order: {
                id: "DESC"
            },
            relations: ["system", "dept"],
        })
    }

    @Post(":name/add")
    @UseLog("添加记录")
    async add(
        @Body() body: Channel,
        @Param("name") name,
        @CurrentUser() user: UserSys
    ) {
        body.gender = (body.gender as any == "true")
        return this.channelService.channel.save(this.channelService.channel.create({
            system: user.system,
            dept: user.dept || await this.deptService.dept.findOne({
                where: {
                    system: {
                        id: user.system.id
                    },
                    name
                }
            }),
            ...body,
        }))
    }

    @Post(":id/upd")
    @UseLog("修改记录")
    upd(
        @Param("id") id: number,
        @Body() body: Channel
    ) {
        body.gender = (body.gender as any == "true")
        return this.channelService.channel.update({ id }, body)
    }

    @Post("del")
    @UseLog("删除记录")
    del(
        @Body() { ids }
    ) {
        return this.channelService.channel.delete({ id: In(ids) })
    }
}
